<template>

    <el-form :model="modelData"
             ref="form"
             label-width="100px">
      <el-form-item label="角色名称" >
        <el-input v-model="modelData.name" disabled> </el-input>
      </el-form-item>

      <el-form-item label="分配权限" >
        <el-tree
          ref="tree"
          :data="dataTree"
          :default-checked-keys="checkedNode"
          node-key="id"
          show-checkbox
          check-strictly>
        </el-tree>
      </el-form-item>

      <el-form-item >
          <el-button @click="handleCancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </el-form-item>
      </el-form>
</template>

<script>
import { putRoleMenu, getRoleMenus } from 'api/admin/role'
import { fetchTree } from 'api/admin/menu'
export default {
  name: 'element',
  data () {
    return {
      modelData: {
        id: 0,
        name: undefined
      },
      modelAuth: [
      ],
      // props: {
      //   label: 'text',
      //   children: 'children'
      // },
      dataTree: [],
      checkedNode: []
    }
  },
  created () {
    fetchTree().then(response => {
      this.dataTree = response.data
    })
  },
  mounted () {
    console.log('mounted')
    this.checkedNode = []
  },
  methods: {
    setModel (data) {
      console.log('setModel')
      this.$refs.tree.setCheckedNodes([])
      if (data) {
        this.modelData.id = data.id
        this.modelData.name = data.name
        getRoleMenus(data.id).then(response => {
          this.modelAuth = response.data
          this.checkedNode = []
          for (let item of this.modelAuth) {
            this.checkedNode.push(item.menuId)
          }
        })
      }
    },
    handleSubmit () {
      // console.log(this.checkedNode)
      // console.log()
      this.update()
    },
    handleCancel () {
      this.$emit('cancel')
    },
    update () {
      let ids = this.$refs.tree.getCheckedKeys()
      putRoleMenu(this.modelData.id, ids.toString()).then(response => {
        let code = parseInt(response.code)
        if (code === 0) {
          this.complete()
        }
      })
    },
    complete () {
      this.checkedNode = []
      this.$refs.form.resetFields()
      this.$emit('complete')
    }
  }
}
</script>
